<?php
if (!defined("_INDEX")) { header("Location: /"); die; }

$errors = array();

$news_id = UV::readInt(strip_tags($route->getAdminId()));
$news = $db->getRow("select * from `news` where `news_id` = '$news_id' limit 1");
if (!$news)
	goToPage("/cabinet/content/list");

$news_tags = $db->getColumn("select `T`.`name` from `tags` as `T`,`news_tags` as `NC` where `T`.`tag_id` = `NC`.`tag_id` and `NC`.`news_id` = '$news_id'");

if (UV::readMQ($route->POST("act")) == 'post')
{
	$user_id = $user->getUserId();
	$title = UV::readMQ(strip_tags($route->POST("title")));
	$preview = UV::readMQ(strip_tags($route->POST("preview"),"<p><h2><h3><blockquote><br/><b><i><sup><strike><ul><li><ol><img><table><tr><td><object><param><embed><a><span>"));
	$text = UV::readMQ(strip_tags($route->POST("full"),"<p><h2><h3><blockquote><br/><b><i><sup><strike><ul><li><ol><img><table><tr><td><object><param><embed><a><span>"));
	$tags = UV::readMQ(strip_tags($route->POST("tags")));
	$status = UV::readMQ(strip_tags($route->POST("status")));
	
	$query = "update `news` set `title`='$title',`preview`='$preview',`text`='$text',`tags`='$tags',`status`='$status' where `news_id` = '$news_id' limit 1";
	if ($db->sendQuery($query))
	{
		// tags
		$db->sendQuery("delete from `news_tags` where `news_id` = '$news_id'");
		$tags = explode(",",$tags);
		foreach ($tags as $tag){
			$e_tag = preg_replace('/ +/',' ',trim($tag));
			if ($e_tag != "")
			{
				$is_tag = $db->getCell("select `tag_id` from `tags` where `name` = '$e_tag'");
				if (!$is_tag){
					$db->sendQuery("insert into `tags` values(NULL,'$e_tag')");
					$is_tag = mysql_insert_id();
				}
				$db->sendQuery("insert into `news_tags` values (NULL,'$is_tag','$news_id')");
			}
		}
		
		$path_name = MAIN_DIR.DS."files".DS."img".DS."news".DS.$news_id;
		
		// загружаем фотки
		if (isset($_FILES['photo']['tmp_name']) && $_FILES['photo']['tmp_name'] != "")
		{
			if (!is_dir($path_name))
				mkdir($path_name);
			if (!is_dir($path_name.DS."small"))
				mkdir($path_name.DS."small");
			if (!is_dir($path_name.DS."big"))
				mkdir($path_name.DS."big");
			
			$photo_size = getimagesize($_FILES['photo']['tmp_name']);
			$photo_name = "x_".time().".".substr(strrchr($_FILES['photo']['name'], '.'), 1);
			$photo = resizeImg($_FILES['photo']['tmp_name'],210,150,$path_name.DS."small".DS.$photo_name);
			if ($photo === true)
				resizeImg($_FILES['photo']['tmp_name'],$photo_size[0],$photo_size[1],$path_name.DS."big".DS.$photo_name);
		}
	}
	else
		$errors[] = "Ошибка редактирования новости";
	if (count($errors) == 0)
		goToPage("/cabinet/news/list");
}

require_once CABINET.DS."head.php";
?>
<link href="/files/js/redactor/css/redactor.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='/files/js/redactor/redactor.js'></script>
<script type='text/javascript'>
$(document).ready(function(){	
	$('#preview_news').redactor({
		toolbar: 'mini',
		image_upload: "/cabinet/news/upload"
	});
	$('#full_news').redactor({
		image_upload: "/cabinet/news/upload"
	});
	
	$("#show_preview").click(function(){
		$("#preview_title").val($("#title").val());
		$("#preview_preview").val($("#preview_news").val());
		$("#preview_link").val($("#link").val());
		$("#preview_text").val($("#full_news").val());
		$("#preview_tags").val($("#tags").val());
		$("#previewForm").submit();
	});
	
	$("#tag_list").change(function(){
		if ($(this).val() != ''){
			var tag_str = $.trim($("#tags").val());
			var tag_ar = tag_str.split(",");
			for (tag in tag_ar)
				tag_ar[tag] = $.trim(tag_ar[tag]);
			var exists = false;
			for(var i = 0, l = tag_ar.length; i < l; i++){
				if (tag_ar[i] == $(this).val()){
					exists = true;
					break;
				}
			}
			if (!exists){
				if (tag_str != '' && tag_str[tag_str.length-1] != ','){
					tag_str += ",";
				}
				tag_str += $(this).val();
				$("#tags").val(tag_str);
			}
		}
	})
});
</script>
<div class="full">
	<div class="submenu_container">
		<a class="submenu_button all_news" href='/cabinet/news/list'>Список новостей</a>
		<a class="submenu_button add_news" href='/cabinet/news/add'>Добавить новость</a>
		<a class="submenu_button submenu_button_active">Редактирование новости</a>
	</div>
	<?php
	if (count($errors) > 0)
		echo "<p style='color:red'>".implode("<br />",$errors)."</p>";
	?>
	<h3>Редактирование новости</h3>
	<div id="contentaddnews">
		<form method='post' enctype="multipart/form-data">
			<input type="hidden" name="act" value='post' />
			<div class="left label clear"><label for='title'>Заголовок</label></div><div class="right"><input type="text" id="title" name="title" value='<?php echo $news['title']?>' /></div>
			<div class="left label clear"><label for='tags'>Теги</label></div><div class="right"><input type="text" id="tags" name="tags" value='<?php echo implode(",",$news_tags); ?>' /></div>
			<div class="left label clear"><label for='tags'>Список тегов</label></div><div class="left" style="margin: 2px 0 0 28px;">
				<select id='tag_list'>
					<option value=''>Выберите тег</option><?php
					$query = "select `T`.`name`
						from `tags` as `T`
						left join `news_tags` as `NT` using (`tag_id`)
						group by `T`.`tag_id` having count(`NT`.`tag_id`) > 0 order by count(`NT`.`tag_id`) desc,`name`";
					$tag_list = $db->getTable($query);
					echo selectCreate($tag_list,"name","name");
				?></select>
			</div>
			<div class="clear">
				<label for='order'>Статус</label>
				<input style="margin-left: 60px" type="radio" name="status" value='placed' <?php if ($news['status'] != 'not') echo "checked='checked'"; ?> /> Размещено
				<input style="margin-left: 10px" type="radio" name="status" value='not' <?php if ($news['status'] == 'not') echo "checked='checked'"; ?> /> В черновиках
			</div>
			<div class="left label clear">Краткое содержание</div>
			<div class="clear"><textarea id='preview_news' name='preview'><?php echo $news['preview']?></textarea></div>
			<div class="left label clear">Текст новости</div>
			<div class="clear"><textarea id='full_news' rows='1' name='full'><?php echo $news['text']?></textarea></div>
			<div class='photos'>
				<label for='photo'>Картинки</label> <input type='file' name='photo' id='photo' />
				<?php
					$photos_path = MAIN_DIR.DS."files".DS."img".DS."news".DS.$news_id.DS."small";
					if (is_dir($photos_path))
					{
						$imgs = array();
						$handle = opendir($photos_path);
						
						while (false !== ($file = readdir($handle)))
							if ($file != "." && $file != "..")
								$imgs[] = $file;
						closedir($handle);
						
						if (count($imgs) > 0)
						{
							$max_in_row = 4;
							echo "<table>";
							$i = 0;
							while ($i < count($imgs))
							{
								echo "<tr>";
								for ($j = 0; $j < $max_in_row && $i < count($imgs); $j++)
									echo "<td><a class='images' rel='group' href='/files/img/news/$news_id/big/".$imgs[$i]."'>
									<img style='border:1px solid black' src='/files/img/news/$news_id/small/".$imgs[$i]."' /></a><br />
									<a class='delete photo' href='/cabinet/news/delete_img?news_id=$news_id&src=".$imgs[$i++]."'>Удалить</a></td>";
								echo "</tr>";
							}
							echo "</table>";
						}
					}
				?>
			</div>
			<div class="right">
				<input type="button" id="show_preview" value="Предварительный просмотр"/> | <input type="submit" value="Опубликовать"/>
			</div>
		</form>
	</div>
	<form id='previewForm' target='_blank' method='post' action="/cabinet/news/preview">
		<input type='hidden' name='preview_title' id='preview_title' />
		<input type='hidden' name='preview_preview' id='preview_preview' />
		<input type='hidden' name='preview_link' id='preview_link' />
		<input type='hidden' name='preview_text' id='preview_text' />
		<input type='hidden' name='preview_tags' id='preview_tags' />
		<input type='hidden' name='preview_time' id='preview_time' value='<?php echo $news['time']; ?>' />
	</form>
</div>

<?php require_once CABINET.DS."footer.php"; ?>
